package refresh;

import java.util.Calendar;
import java.util.Hashtable;

import net.rim.device.api.system.PersistentObject;
import net.rim.device.api.system.PersistentStore;
import webservice.WebServiceURLs;
import beans.WsTimestamp;

public class RefreshData {

	//0xc348b0df1b6cb526L
	
	private PersistentObject po;
	private Hashtable ht;
	
	public RefreshData(){
		po = PersistentStore.getPersistentObject(0xc348b0df1b6cb526L);
		synchronized (po) {
			ht = (Hashtable) po.getContents();
			if (ht==null){
				ht = new Hashtable();
				po.setContents(ht);
				po.commit();
			}
		}
	}
	
	public Object get(String key){
		return ht.get(key);
	}
	
	public void set (String key, Object currentTime){
		ht.put(key, currentTime);
	}
	
	public void commit(){
		po.commit();
	}
	
	/*
	 * Ws values:
	 * getPeriodosClase : PC
	 * getMoreInfoClase : MIC
	 * getGrupo : G
	 * Hashtable key: ws+aulaID (concat)
	 * Hashtable value: timestamp from last login
	 */
	
	public boolean mustCheckWs(String ws, String string){
		String key = ws+string;
		Object o = this.get(key);
		WsTimestamp currentTime = new WsTimestamp(Calendar.getInstance().getTime().getTime());
		if (o==null){
			this.set(key, (Object)currentTime);
		} else {
			WsTimestamp timestamp = (WsTimestamp)o;
			if (currentTime.getMilis()-timestamp.getMilis()>WebServiceURLs.REFRESH_RATE){
				this.set(key, currentTime);
			}
			else{
				return false;
			}
		}
		return true;
	}
}
